package com.qianchang.microfinance.view.mine.bill;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.StringUtils;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.ClearEditText;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.MerchantPayApplyBean;
import com.qianchang.microfinance.bean.MyBillBean;
import com.qianchang.microfinance.bean.ThpinfoBean;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.tlpay.TlPayInputActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.qianchang.microfinance.global.ConstantAppInfo.DEFAULT_TIME;

/********
 *   通联支付页面详情 订单号，订单金额显示 2018.7.16
 *
 */

public class TLPayDetailsActivity extends BaseActivity{

    @BindView(R.id.tv_get_phone_code)
    DTextView tvGetPhoneCode;
    @BindView(R.id.et_indentify_code)
    ClearEditText etMSNText;
    @BindView(R.id.tv_ordmoney_id)
    TextView tvMoney;
    @BindView(R.id.tv_orderNub_id)
    TextView tvOrderNub;


    private static int RESCODE = 2;
    private CountDownTimer phoneDownTimer;
    private MyBillBean.Bean bean;
    private MerchantPayApplyBean merchantPayApplyBean;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tlpaydetails_layout);
        ButterKnife.bind(this);
        initView();
        initData();

        tlMerchantPayApply();           //第一步,先发送商户支付申请

    }


    @Override
    protected void initView() {
        super.initView();
        setTitle("支付详情");

    }

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getBundle();
        bean = (MyBillBean.Bean) bundle.getSerializable(MyBillAdapter.ENTITY_KEY);
        Log.i("wmy", "initData bean = " + bean.toString());
    }

    @OnClick({R.id.bt_truepay_id,R.id.tv_get_phone_code})
    public void onViewClicked(View view) {
        int vId = view.getId();
        switch (vId){
            case R.id.bt_truepay_id:            //确认支付按钮
//                startActivity(TLPaySusOrFailActivity.class);            //跳转银行卡录入界面

                payConfirm();

                break;
            case R.id.tv_get_phone_code:            //获取短信验证码

                showRemainTime();
                if(getIsApplySus()){            //第二步，如果商户支付申请成功，重新获取支付短信（使用重新获取支付短信）
                    resendMerchantMsnCode();
                }else {
                    tlMerchantPayApply();           //第一步,先发送商户支付申请
                }

                break;
            default:
                break;
        }
    }



//    private static final int DEFAULT_TIME = 10 * 1000;//获取验证码的时间周期      测试使用，不用时候直接删掉
    //显示获取手机验证码倒计时
    private void showRemainTime() {
        tvGetPhoneCode.setEnabled(false);
        phoneDownTimer = new CountDownTimer(DEFAULT_TIME, 1000) {
            @SuppressLint("NewApi")
            @Override
            public void onTick(long millisUntilFinished) {
                int temp = (int) (millisUntilFinished / 1000);
                tvGetPhoneCode.setText("重新获取 " + temp + "S");//getString(R.string.remain_time) +
                tvGetPhoneCode.setEnabled(false);
//                tvGetPhoneCode.setTextColor(getResources().getColor(R.color.common_text_hint_color,null));
                tvGetPhoneCode.setTextColor(ContextCompat.getColor(getApplicationContext(),R.color.common_text_hint_color));
            }

            @SuppressLint("NewApi")
            @Override
            public void onFinish() {
                tvGetPhoneCode.setText(getString(R.string.btn_reacquire_code));
                tvGetPhoneCode.setEnabled(true);
//                tvGetPhoneCode.setTextColor(getResources().getColor(R.color.getCodeTextColor_blue,null));
                tvGetPhoneCode.setTextColor(ContextCompat.getColor(getApplicationContext(),R.color.getCodeTextColor_blue));
            }
        }.start();

    }


    //设置签约申请成功标识
    private boolean isApplySus = false;
    private void setIsApplySus(boolean flag){
        this.isApplySus = flag;
    }

    private boolean getIsApplySus(){
        return isApplySus;
    }



    //商户支付申请（发起支付接口）
    private void tlMerchantPayApply(){

        String projectId = "";
        String period = "";
        String userId = DMApplication.getInstance().getmUserLoginInfo().getUserId();

        if(bean != null){
            projectId = bean.getProjectId();
            period = bean.getPeriod();
        }

        HttpParams params = new HttpParams();
        params.put("projectId",projectId);
        params.put("period",period);
        params.put("meruserid",userId);
        params.put("userId",userId);
        params.put("rechargeType",9);

        show();
        DMOKHttpUtils.getInstance().post(TLPayDetailsActivity.this, DMConstant.ApiURL.TL_MERCHANTPAYAPPLY, params, new RequestCallBack<MerchantPayApplyBean>() {

            @Override
            public void onSuccess(JsonResult<MerchantPayApplyBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    setIsApplySus(true);    //设置商户支付申请是否成功
                    merchantPayApplyBean = response.getObject();
                    setUiData(merchantPayApplyBean);
                    showRemainTime();
                }else {
                    setIsApplySus(false);
                    merchantPayApplyBean = null;
                    setUiData(null);
                    ToastUtil.getInstant().show(TLPayDetailsActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                setIsApplySus(false);
                merchantPayApplyBean = null;
                setUiData(null);
                ToastUtil.getInstant().show(TLPayDetailsActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                setIsApplySus(false);
                merchantPayApplyBean = null;
                setUiData(null);
            }
        });
    }


    private void setUiData(MerchantPayApplyBean merchantPayApplyBean){
        if(merchantPayApplyBean != null && (!merchantPayApplyBean.equals(""))){
            tvMoney.setText("¥ " + merchantPayApplyBean.getAmount());
            tvOrderNub.setText(merchantPayApplyBean.getOrderno());
        }else {
            tvMoney.setText("");
            tvOrderNub.setText("");
        }
    }



    //重新获取支付短信（使用重新获取支付短信）

    private void resendMerchantMsnCode(){

        String orderid = "";
        String thpinfo = "";
        if(merchantPayApplyBean != null){
            orderid = merchantPayApplyBean.getOrderid();
            thpinfo = merchantPayApplyBean.getThpinfo();
        }
        HttpParams params = new HttpParams();
        params.put("orderid",orderid);
        params.put("thpinfo",thpinfo);

        String projectId = "";
        String period = "";
        String userId = DMApplication.getInstance().getmUserLoginInfo().getUserId();
        String rechargeType = "9";      //逾期默认传9

        if(bean != null){
            projectId = bean.getProjectId();
            period = bean.getPeriod();
        }
        params.put("projectId",projectId);
        params.put("period",period);
        params.put("meruserid",userId);
        params.put("userId",userId);
        params.put("rechargeType",rechargeType);

        show();
        DMOKHttpUtils.getInstance().post(TLPayDetailsActivity.this, DMConstant.ApiURL.TL_AGAINACQUIREPAYSMS, params, new RequestCallBack<ThpinfoBean>() {

            @Override
            public void onSuccess(JsonResult<ThpinfoBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {

                }else {
                    ToastUtil.getInstant().show(TLPayDetailsActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(TLPayDetailsActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }
        });
    }

    //支付确认（使用支付确认）
    private void payConfirm(){

        String msn = etMSNText.getText().toString();
        if (StringUtils.isEmptyOrNull(msn)) {
            ToastUtil.getInstant().show(this, getString(R.string.input_indentity));
            return;
        }

        String orderid = "";
        String thpinfo = "";
        String smscode = msn;
        String trxid = "";

        if(merchantPayApplyBean != null){
            orderid = merchantPayApplyBean.getOrderid();
            thpinfo = merchantPayApplyBean.getThpinfo();
            trxid = merchantPayApplyBean.getTrxid();
        }

        HttpParams params = new HttpParams();
        params.put("orderid",orderid);
        params.put("thpinfo",thpinfo);
        params.put("smscode",smscode);
        params.put("trxid",trxid);

        String rechargeType = "9";      //逾期默认传9
        String projectId = "";
        String period = "";
        String userId = DMApplication.getInstance().getmUserLoginInfo().getUserId();
        if(bean != null){
            projectId = bean.getProjectId();
            period = bean.getPeriod();
        }
        params.put("projectId",projectId);
        params.put("period",period);
        params.put("meruserid",userId);
        params.put("userId",userId);
        params.put("rechargeType",rechargeType);
        show();
        DMOKHttpUtils.getInstance().post(TLPayDetailsActivity.this, DMConstant.ApiURL.TL_PAYCONFIRM, params, new RequestCallBack<ThpinfoBean>() {

            @Override
            public void onSuccess(JsonResult<ThpinfoBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    startActivity(TLPaySusOrFailActivity.class);
                    setResult(RESCODE);
                    TLPayDetailsActivity.this.finish();
                }else {
                    ToastUtil.getInstant().show(TLPayDetailsActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(TLPayDetailsActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }
        });
    }


}
